/*
 * FileBrowser.java
 *
 * Created on 8 2007, 20:50
 *
 * Note: This source code is protected under the This software is licensed under the CC-GNU GPL.
 */
package OpenToday.Configuration;

import java.util.Enumeration;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.io.file.FileSystemRegistry;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;


/**
 *
 * @author Menny Even Danan (c) 2007. Note: This source code is protected under the This software is licensed under the CC-GNU GPL.
 */
public class FileBrowser extends List implements CommandListener, Runnable {

    private String m_selectedValue;
    private String m_currentFoldersPath;
    private final IFileBrowserCreator m_manager;
    private Thread m_currentThread;

    public FileBrowser(IFileBrowserCreator manager, String startPoint) {
        super("Files", List.IMPLICIT);
        m_manager = manager;
        m_selectedValue = "";
        m_currentFoldersPath = startPoint;
        if (m_currentFoldersPath.indexOf('/') > 0) {
            m_currentFoldersPath = m_currentFoldersPath.substring(0, m_currentFoldersPath.lastIndexOf('/'));
        }
        m_currentThread = new Thread(this, "FileBrowser entires reader");
        m_currentThread.start();
        super.setSelectCommand(new Command("Select", Command.OK, 1));
        super.addCommand(new Command("Cancel", Command.CANCEL, 1));
        super.setCommandListener(this);
    }

    public void commandAction(Command command, Displayable displayable) {
        if (command.getCommandType() == Command.OK) {
            try {
                if (super.getSelectedIndex() >= 0) {
                    String selectedItem = super.getString(super.getSelectedIndex());
                    System.out.println("Selected item is: " + selectedItem);
                    if (selectedItem.equals("..")) {//one folder up
                        m_selectedValue = "";
                        m_currentFoldersPath = ReGenerateWithOneFolderUp(m_currentFoldersPath);
                        System.out.println("Moving one folder up: " + m_currentFoldersPath);
                    } else {//something selected
                        m_selectedValue = selectedItem;
                        System.out.println("New selectedValue: " + m_selectedValue);
                    }
                    //why another thread? Must be done like this to prevent a deadlock
                    m_currentThread = new Thread(this, "FileBrowser entires reader");
                    m_currentThread.start();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                m_manager.OnError(ex.getMessage());
            }
        } else if (command.getCommandType() == Command.CANCEL) {
            m_manager.OnCancel();
        }
    }

    private void buildFilesList() {
        System.out.println("Clearing the file list");
        super.deleteAll();
        Vector rootItems = new Vector();
        if ((m_currentFoldersPath.length() == 0) && (m_selectedValue.length() == 0)) {//SE root elements
            super.setTitle("Root");
            System.out.println("Reading root list");
            Enumeration roots = FileSystemRegistry.listRoots();
            while (roots.hasMoreElements()) {
                Object oRoot = roots.nextElement();
                System.out.println("Root entry: " + oRoot);
                rootItems.addElement(oRoot.toString());
            }
        } else {//removing the filename, staying with the path, and openning it
            try {
                String path = m_currentFoldersPath;
                if (m_selectedValue.length() > 0) {
                    path = path + m_selectedValue;
                    super.setTitle(m_selectedValue);
                } else {
                    super.setTitle(m_currentFoldersPath);
                }
                //if (path.endsWith("/"))
                //    path = path.substring(0, path.length() - 1);//removing last /
                System.out.println("Opening: " + path);
                FileConnection fs = null;
                try {
                    fs = (FileConnection) Connector.open("file:///" + path, Connector.READ);
                    if (fs.isDirectory()) {
                        m_currentFoldersPath = path;
                        System.out.println("Reading list of " + path);
                        Enumeration e = fs.list();
                        super.append("..", null);
                        while (e.hasMoreElements()) {
                            Object file = e.nextElement();
                            System.out.println("Dir entire: " + file);
                            rootItems.addElement(file.toString());
                        }
                    } else {
                        System.out.println("Selected a new file " + path);
                        System.out.println("Selected a file : " + path);
                        m_manager.OnNewImageSelected(path);
                        return;//no need to update list
                    }
                } finally {
                    try {
                        if (fs != null) {
                            fs.close();
                        }
                    } catch (Exception ex) {
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                m_manager.OnError(ex.getMessage());
                return;//error!
            }
        }
        //populating list
        for (int i = 0; i < rootItems.size(); i++) {
            super.append((String) rootItems.elementAt(i), null);
        }
    }

    public void run() {
        buildFilesList();
    }

    private static String ReGenerateWithOneFolderUp(String currentFoldersPath) {
        //in case of no-up (i.e., 'root1/'), will return empty string
        int firstSlash = currentFoldersPath.indexOf('/');
        if (firstSlash == -1)//if no slashes, will move to roots (empy string)
        {
            System.out.println("From " + currentFoldersPath + " moving to roots! Weird path.");
            return "";
        } else {
            int lastSlash = currentFoldersPath.lastIndexOf('/');
            if (firstSlash == lastSlash) {
                System.out.println("From " + currentFoldersPath + " moving to roots! Just the root folder left");
                return "";
            } else {
                String withoutLastSlash = currentFoldersPath.substring(0, lastSlash);
                int secondLastSlash = withoutLastSlash.lastIndexOf('/');
                String withoudSecondLastSlash = withoutLastSlash.substring(0, secondLastSlash);
                System.out.println("From " + currentFoldersPath + " moving to " + withoudSecondLastSlash);
                return withoudSecondLastSlash + '/';//I need the last slash
            }
        }
    }
}
